package com.lapost.client;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;


import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ReceivedListActivity extends ListActivity {

	public static final String TAG = ReceivedListActivity.class.getSimpleName();
	ListAdapter adapter;
	Context context;

	
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        context=this;
        overridePendingTransition(R.anim.hold, R.anim.push_left_in);

        // We'll define a custom screen layout here (the one shown above), but
        // typically, you could just use the standard ListActivity layout.
        //setContentView(R.layout.list_layout);
        this.getListView().setCacheColorHint(0);
        this.getListView().setDivider(this.getResources().getDrawable(R.drawable.transparent_color));
        this.getListView().setDividerHeight(2);
        new ProgressTask(ReceivedListActivity.this).execute();

    }
    
    protected void loadListContent() {
        List<Map<String, String>> data = new ArrayList<Map<String,String>>(); 
    	try {
    		String receiver = URLEncoder.encode(Constants.userName, "UTF-8");
			JSONArray json = new JSONArray(HttpHelper.doGet("letter?receiver='" + receiver + "'"));
			for(int i=0; i < json.length(); i++) {
				JSONObject obj = (JSONObject) json.get(i); 
				Log.i(TAG, obj.toString());
				Map<String, String> map = new HashMap<String, String>();
				map.put("identifier", getString(R.string.num) + obj.getString("identifier"));
				map.put("nameSender", "De " + obj.getString("nameSender"));
				map.put("type", obj.getString("type"));

				//map.put("state", "Statut: " + obj.getString("state"));
				
				
				String identifier = URLEncoder.encode((String)obj.getString("identifier"), "UTF-8");
				JSONArray jsonStateHistory = new JSONArray(HttpHelper.doGet("state_history?id='"+identifier+"'"));

				String stateHistory="";
				
				for(int j=jsonStateHistory.length()-1; j >=0 ; j--) {
					
					JSONObject jsonObjStateHistoryElement = (JSONObject) jsonStateHistory.get(j); 
					
					JSONObject historyElementObj = (JSONObject) jsonObjStateHistoryElement; 

					stateHistory=stateHistory+"\n"+" Le "+historyElementObj.getString("date")+" "+historyElementObj.getString("state")+"\n";
					
					if(j==jsonStateHistory.length()-1){
					map.put("state", " Statut: " + "\n Le "+historyElementObj.getString("date")+" "+historyElementObj.getString("state"));
					}

					
					Log.i(TAG+"stateHistory=", stateHistory);

				}
				
				map.put("stateHistory", "Historiques:\n" + stateHistory);

				
				data.add(map);
			}
				
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
         adapter = new SimpleAdapter(
                this, 
                data,  
                R.layout.list_item_layout,                            
                new String[] {"identifier", "nameSender", "state", "type"},           
                new int[] {R.id.identifier, R.id.name, R.id.state, R.id.type});  

        
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.receive_options, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.refresh:
                new ProgressTask(ReceivedListActivity.this).execute();
            	return true;
            case R.id.me:
            	Intent info = new Intent(this, UserInfoActivity.class);
                startActivity(info);
            	return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }    
    
    
    private void openDialog(String identifier,String nameSender,String state){
    	
    	
    	final Dialog d = new Dialog(this,R.style.CustomDialogTheme);
    	d.setContentView(R.layout.detailed_letter_info);
    	
    	
    	TextView identifierView = (TextView) d.findViewById(R.id.identifier);
    	TextView nameSenderView = (TextView) d.findViewById(R.id.name);
    	TextView stateView = (TextView) d.findViewById(R.id.state);
    	
    	TextView addrReceiverView = (TextView) d.findViewById(R.id.addrReceiver);
    	addrReceiverView.setVisibility(View.GONE);

    	
    	identifierView.setText(identifier);
    	nameSenderView.setText(nameSender);
    	stateView.setText(state);
    	
    	d.show();
    	
    }
    
    
    @Override  
    protected void onListItemClick(ListView l, View v, int position, long id) {  
     	HashMap data=(HashMap)adapter.getItem(position);
    	
    		Intent wake = new Intent(this, LetterDetailActivity.class);
    		wake.putExtra("letter", data.get("identifier").toString().replace(getString(R.string.num), "").trim());
    		wake.putExtra("SENT_LIST_OR_RECEIVED_LIST", "RECEIVED_LIST");
    		startActivity(wake);
          
          super.onListItemClick(l, v, position, id);  
    }
    
    
    
    private class ProgressTask extends AsyncTask<String, Void, Boolean> {
        private ProgressDialog dialog;
    
        public ProgressTask(ListActivity activity) {
            
            dialog = new ProgressDialog(context);
        }




    protected void onPreExecute() {
    	this.dialog.setTitle("La Poste");
        this.dialog.setIcon(R.drawable.icon_mini);
        this.dialog.setMessage("Chargement en cours...");
        this.dialog.setProgressStyle(R.style.CustomDialogTheme);
        this.dialog.setCancelable(false);
        this.dialog.show();
    }

        @Override
    protected void onPostExecute(final Boolean success) {
         
            
        	 setListAdapter(adapter);
             
            if (dialog.isShowing()) {
            dialog.dismiss();
        }

        if (success) {
            //Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(context, "Erreur de connexion", Toast.LENGTH_LONG).show();
        }
    }

    protected Boolean doInBackground(final String... args) {
        try{    
           
        	loadListContent();

            return true;
         } catch (Exception e){
            Log.e("tag", "error", e);
            return false;
         }
      }


}
    
    
    protected void onPause(){
 	   
        overridePendingTransition(R.anim.push_left_out, R.anim.hold);
        super.onPause();

    }
    
    protected void onResume(){
 	   if(Constants.shouldRefreshReceivedList){
        new ProgressTask(ReceivedListActivity.this).execute();
        Constants.shouldRefreshReceivedList=false;
 	   }
        super.onResume();
     }
    
    

}
